package com.iseastar.guojiang.team;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.TextAppearanceSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.iseastar.BaseActivity2;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.dialog.DialogMgr;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.AppLogic;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.CourierTeamCenterHomeBean;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.TeamHomeBannerBackBean;
import com.shouhuobao.station.R;
import com.shouhuobao.take.model.BannerBean;
import com.shouhuobao.take.utils.StringUtils;
import com.shouhuobao.take.weight.banner.Banner;
import com.shouhuobao.take.weight.banner.BannerConfig;
import com.shouhuobao.take.weight.banner.Transformer;
import com.shouhuobao.take.weight.banner.listener.OnBannerListener;
import com.shouhuobao.take.weight.banner.loader.GlideImageLoader;

import java.util.ArrayList;

import droid.frame.ui.view.VerticalTextview;

/**
 * @author 李澄锋<br>
 * 2018/6/11
 * 火箭侠中心
 */
public class CourierTeamCenterActivity extends BaseActivity2 implements View.OnClickListener, OnBannerListener {

    private Banner mBanner;
    private VerticalTextview mTeamDynamicMsgTV;
    private ViewGroup mUnCreateTeamLayout;
    private ViewGroup mCreatingTeamLayout;
    private ViewGroup mCreatedTeamLayout;

    private CountDownTimer timer = null;
    private CourierTeamCenterHomeBean teamCenterHomeBean = null;
    private boolean isRequest = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showLoadingDialog(null);
        AppHttp.getInstance().teamCenterHoneData();
        AppHttp.getInstance().getTeamHomeBannerData();
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_courier_team_center);
        super.findViewById();
        getAppTitle().setCommonTitle("战队中心");
        mBanner = findViewById(R.id.banner);
        mTeamDynamicMsgTV = findViewById(R.id.team_dynamic_msg_tv);
        mTeamDynamicMsgTV.setText(12, 0, Color.parseColor("#3E648C"));
        mTeamDynamicMsgTV.setTextStillTime(3000);//设置停留时长间隔
        mTeamDynamicMsgTV.setAnimTime(300);//设置进入和退出的时间间隔
        //创建战队
        mUnCreateTeamLayout = findViewById(R.id.create_team_layout);
        mUnCreateTeamLayout.setOnClickListener(this);
        //创建中战队
        mCreatingTeamLayout = findViewById(R.id.creating_team_layout);
        mCreatingTeamLayout.setOnClickListener(this);
        //我的战队
        mCreatedTeamLayout = findViewById(R.id.my_team_layout);
        mCreatedTeamLayout.setOnClickListener(this);
        //查看本战区战队
        findViewById(R.id.team_zone_layout).setOnClickListener(this);
        //查看全网战队
        findViewById(R.id.all_team_zone_layout).setOnClickListener(this);
        setBannerData(null);
    }

    /**
     * 设置banner数据
     */
    public void setBannerData(ArrayList<BannerBean> items) {
        if (mBanner == null) {
            return;
        }
        //设置banner样式
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置banner加载器
        mBanner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        mBanner.setBannerList(items);
        //设置banner动画效果
        mBanner.setBannerAnimation(Transformer.Default);
        //设置自动轮播，默认为true
        mBanner.isAutoPlay(true);
        //设置轮播时间
        mBanner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        mBanner.setOnBannerListener(this);
        //banner设置方法全部调用完毕时最后调用
        mBanner.start();

    }

    /**
     * 更新首页界面
     *
     * @param courierTeamCenterHomeBean
     */
    private void updataView(CourierTeamCenterHomeBean courierTeamCenterHomeBean) {
        this.teamCenterHomeBean = courierTeamCenterHomeBean;
        if (courierTeamCenterHomeBean == null) {
            return;
        }
        //1:审核中，2：通过，3：未加入
        if (courierTeamCenterHomeBean.getTeamFlag() == 1) {
            mUnCreateTeamLayout.setVisibility(View.GONE);
            mCreatingTeamLayout.setVisibility(View.VISIBLE);
            mCreatedTeamLayout.setVisibility(View.GONE);
            //战队名称
            ((TextView) findViewById(R.id.team_name_tv)).setText(courierTeamCenterHomeBean.getTeamName());
            //设置队长布局
            if (courierTeamCenterHomeBean.isTeamLeader()) {
                findViewById(R.id.team_leader_layout).setVisibility(View.VISIBLE);
                if (courierTeamCenterHomeBean.isCheckFlag()) {
                    findViewById(R.id.courier_new_message_iv).setVisibility(View.VISIBLE);
                } else {
                    findViewById(R.id.courier_new_message_iv).setVisibility(View.GONE);
                }
            } else {
                findViewById(R.id.team_leader_layout).setVisibility(View.INVISIBLE);
            }
            ((TextView) findViewById(R.id.team_member_tv)).setText("差" + courierTeamCenterHomeBean.getOtherCourierNum() + "个人组队成功");
            //战队组队剩余时间
            //当前时间大于解散时间,默认为解散了，然后展示为创建团队视图
            if (System.currentTimeMillis() > courierTeamCenterHomeBean.getTeamCancelTime()) {
                mUnCreateTeamLayout.setVisibility(View.VISIBLE);
                mCreatingTeamLayout.setVisibility(View.GONE);
                mCreatedTeamLayout.setVisibility(View.GONE);
            } else {
                final TextView teamResidueTimeTV = findViewById(R.id.team_residue_time_tv);
                long diffTime = courierTeamCenterHomeBean.getTeamCancelTime() - System.currentTimeMillis();
                remaintimeCountdown(teamResidueTimeTV, diffTime);
                timer = new CountDownTimer(diffTime, 60 * 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        remaintimeCountdown(teamResidueTimeTV, millisUntilFinished);
                    }

                    @Override
                    public void onFinish() {
                        mUnCreateTeamLayout.setVisibility(View.VISIBLE);
                        mCreatingTeamLayout.setVisibility(View.GONE);
                        mCreatedTeamLayout.setVisibility(View.GONE);
                    }
                };
                timer.start();
            }
        } else if (courierTeamCenterHomeBean.getTeamFlag() == 2) {
            mUnCreateTeamLayout.setVisibility(View.GONE);
            mCreatingTeamLayout.setVisibility(View.GONE);
            mCreatedTeamLayout.setVisibility(View.VISIBLE);
            //战队名称
            ((TextView) findViewById(R.id.my_team_name_tv)).setText(courierTeamCenterHomeBean.getTeamName());
            //总单量
            ((TextView) findViewById(R.id.my_team_total_order_num_tv)).setText("总单量：" + courierTeamCenterHomeBean.getTaskCount() + "单");
            //总里程
            ((TextView) findViewById(R.id.my_team_total_distance_tv)).setText("总里程：" + courierTeamCenterHomeBean.getTaskDistince() + "公里");
            //总收入
            ((TextView) findViewById(R.id.my_team_total_money_tv)).setText("累计总收入：" + courierTeamCenterHomeBean.getTaskProfit() + "元");
            //战队人数
            ((TextView) findViewById(R.id.my_team_member_tv)).setText(courierTeamCenterHomeBean.getCourierNum() + "");
            //设置队长布局
            if (courierTeamCenterHomeBean.isTeamLeader()) {
                findViewById(R.id.my_team_leader_layout).setVisibility(View.VISIBLE);
                if (courierTeamCenterHomeBean.isCheckFlag()) {
                    findViewById(R.id.my_team_new_message_iv).setVisibility(View.VISIBLE);
                } else {
                    findViewById(R.id.my_team_new_message_iv).setVisibility(View.GONE);
                }
            } else {
                findViewById(R.id.my_team_leader_layout).setVisibility(View.INVISIBLE);
            }
        } else {
            mUnCreateTeamLayout.setVisibility(View.VISIBLE);
            mCreatingTeamLayout.setVisibility(View.GONE);
            mCreatedTeamLayout.setVisibility(View.GONE);
        }
        //本战区战队数量
        ((TextView) findViewById(R.id.this_zone_team_num)).setText(courierTeamCenterHomeBean.getStoreTeamCount() + "");
        //全国战队数
        ((TextView) findViewById(R.id.all_team_num_tv)).setText(courierTeamCenterHomeBean.getTotalTeamCount() + "");
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        mBanner.startAutoPlay();
        mTeamDynamicMsgTV.startAutoScroll();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isRequest) {
            AppHttp.getInstance().teamCenterHoneData();
            AppHttp.getInstance().getTeamHomeBannerData();
        }
        isRequest = false;
    }

    @Override
    public void onStop() {
        super.onStop();
        isRequest = true;
        //结束轮播
        mBanner.stopAutoPlay();
        mTeamDynamicMsgTV.stopAutoScroll();
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            //创建战队
            case R.id.create_team_layout:
                DialogMgr.createATeamRuleDialog(getContext());
                break;
            //创建中战队
            case R.id.creating_team_layout:
                if (teamCenterHomeBean == null) {
                    return;
                }
                intent = new Intent(getContext(), CourierTeamCenterDetailActivity.class);
                intent.putExtra("type", 0);
                intent.putExtra("teamId", teamCenterHomeBean.getTeamId());
                startActivity(intent);
                break;
            //我的战队
            case R.id.my_team_layout:
                intent = new Intent(getContext(), CourierTeamCenterDetailActivity.class);
                intent.putExtra("type", 1);
                intent.putExtra("teamId", teamCenterHomeBean.getTeamId());
                startActivity(intent);
                break;
            //查看本战区战队
            case R.id.team_zone_layout:
                startActivity(TeamCenterZoneListActivity.class);
                break;
            //查看全网战队
            case R.id.all_team_zone_layout:
                startActivity(CourierAllTeamRankingListActivity.class);
                break;
        }
    }

    @Override
    public void OnBannerClick(int position) {
        if (mBanner.getBannerBeanList() == null || mBanner.getBannerBeanList().size() == 0 || null == mBanner.getBannerBeanList().get(position).getOpenType()) {
            return;
        }
        if (StringUtils.isEmpty(mBanner.getBannerBeanList().get(position).getImgUrl())) {
            if (0 != mBanner.getBannerBeanList().get(position).getImgRes()) {
                AppLogic.disposeBannerData(getContext(), mBanner.getBannerBeanList().get(position));
            } else {
                return;
            }
        }
        AppLogic.disposeBannerData(getContext(), mBanner.getBannerBeanList().get(position));
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //战队相关状态数据返回
            case MsgID.courier_team_center_home_data:
                cancelLoadingDialog();
                final ReqResult<CourierTeamCenterHomeBean> result = JSON.parser(msg.obj, CourierTeamCenterHomeBean.class);
                if (checkLoginStatus(result)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updataView(result.getResult());
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return true;
            //获取首页banner
            case MsgID.courier_team_home_banner:
                final ReqResult<TeamHomeBannerBackBean> reqResult = JSON.parser(msg.obj, TeamHomeBannerBackBean.class);
                if (checkLoginStatus(reqResult)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            TeamHomeBannerBackBean backBean = reqResult.getResult();
                            if (backBean != null) {
                                setBannerData(backBean.getBannList());
                                ArrayList<String> messageList = new ArrayList<>();
                                for (TeamHomeBannerBackBean.NoticeDto content : backBean.getNoticeList()) {
                                    messageList.add(content.getNoticeContent());
                                }
                                mTeamDynamicMsgTV.setTextList(messageList);
                            }
                        }
                    });
                } else {
                    showToast(reqResult.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    private void remaintimeCountdown(TextView countDown, long remainTime) {
        String[] diffs = AppLogic.timeDiffDHMSStr(remainTime);
        String timeText = "";
        if (diffs.length == 0) {
            timeText = "00 天 00 小时 00 分";
        } else if (diffs.length == 1) {
            timeText = "00 天 00 小时 00 分";
        } else if (diffs.length == 2) {
            timeText = "00 天 " + "00 小时 " + diffs[0] + " 分";
        } else if (diffs.length == 3) {
            timeText = "00 天 " + diffs[0] + " 小时 " + diffs[1] + " 分";
        } else if (diffs.length == 4) {
            timeText = diffs[0] + " 天 " + diffs[1] + " 小时 " + diffs[2] + " 分";
        }
        int sencondStart = timeText.indexOf(":");
        SpannableString secondSp = new SpannableString(timeText);
        secondSp.setSpan(new TextAppearanceSpan(getContext(), R.style.team_count_down_style), sencondStart + 1, timeText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        countDown.setText("组队剩余组队时间：" + secondSp, TextView.BufferType.SPANNABLE);
    }

    @Override
    protected void onDestroy() {
        if (timer != null) {
            timer.cancel();
        }
        super.onDestroy();
    }
}
